package com.xhwl.logistics.controller.logistics;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.logistics.enums.logistics.CardTypeEnum;
import com.xhwl.logistics.logistics.request.ApprovalParam;
import com.xhwl.logistics.logistics.request.VisitorRecordRequestParam;
import com.xhwl.logistics.query.VisitorRecordQuery;
import com.xhwl.logistics.service.logistics.IVisitorRecordService;
import com.xhwl.logistics.util.PageResult;
import com.xhwl.logistics.vo.logistics.VisitorRecordVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 物流车预约 前端控制器
 * </p>
 *
 * @author lin.yang
 * @since 2023-12-06
 */
@Api(tags = "物流车-物流预约")
@RestController
@Slf4j
@RequestMapping("/logistics/visitor-record-request")
public class VisitorRecordController {

    @Autowired
    private IVisitorRecordService visitorRecordService;


    @ApiOperation(value = "分页物流车预约记录")
    @PostMapping(value = "pageVisitorRecordRequest")
    ResultJson<PageResult<VisitorRecordVO>> pageVisitorRecordRequest(@RequestBody VisitorRecordQuery query){
        log.info("pageVisitorRecordRequest() called with parameters => 【query = {}】",query);
        return this.visitorRecordService.pageVisitorRecordRequest(query);
    }

    @ApiOperation(value = "物流车预约列表查询")
    @PostMapping(value = "queryVisitorRecordRequest")
    public ResultJson queryVisitorRecordRequest(@RequestBody VisitorRecordQuery query){
        log.info("queryVisitorRecord() called with parameters => 【query = {}】",query);
        return visitorRecordService.queryVisitorRecord(query);
    }

    @ApiOperation(value = "保存物流物流车预约")
    @Transactional
    @PostMapping(value = "saveOrUpdateVisitorRecordRequest")
    public ResultJson saveOrUpdateVisitorRecordRequest( @RequestBody VisitorRecordRequestParam params, Account account){
        log.info("saveOrUpdateVisitorRecord() called with parameters => 【params = {}】",params);
        if (ObjectUtil.isNull(params.getAvailableStartDate())||ObjectUtil.isNull(params.getAvailableEndDate())) {
            return ResultJson.fail("有效时间不能为空");
        }
        if (DateUtil.compare(params.getAvailableEndDate(),DateUtil.date())<0) {
            return ResultJson.fail("预约有效时间区间无效！");
        }
        if (ObjectUtil.isNull(params.getPromoter())) {
            //发起人为空的，我们从account中获取
            params.setPromoter(account.getName());
        }
        return this.visitorRecordService.saveOrUpdateVisitorRecord(params);
    }

    @ApiOperation(value = "详情物流车物流车预约")
    @PostMapping(value = "detailVisitorRecordRequest")
    public ResultJson<VisitorRecordVO> detailVisitorRecordRequest(@RequestBody VisitorRecordQuery query){
        log.info("detailVisitorRecord() called with parameters => 【query = {}】",query);
        return this.visitorRecordService.detailVisitorRecord(query);
    }


    @ApiOperation(value = "导出物流预约记录")
    @GetMapping(value = "exportVisitorRecord")
    public void exportVisitorRecord(VisitorRecordQuery query, HttpServletResponse response, HttpServletRequest request) throws IOException {
        log.info("exportVehicleAccess() called with parameters => 【query = {}】, 【response = {}】, 【request = {}】",query, response, request);
        String name= Optional.ofNullable(request).map(x->x.getHeader("name")).orElse(null);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //设置文件名
        String fileName = URLEncoder.encode(ObjectUtil.isNull(name)? "物流预约导出":name,"UTF-8");// URLEncoder.encode(exportHistory.getFileName(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        List<VisitorRecordVO> list =Optional.ofNullable(this.visitorRecordService.queryVisitorRecord(query))
                .map(x->x.getResult()).orElse(Collections.emptyList());
        for (VisitorRecordVO visitorRecordVO : list) {
            visitorRecordVO.setCardTypeText(
                    Arrays.stream(CardTypeEnum.values()).filter(x->x.getCode().equals(visitorRecordVO.getCardType()))
                            .map(x->x.getLabel()).findFirst().orElse(null)
            );
        }
        try {
            EasyExcel.write(response.getOutputStream(),VisitorRecordVO.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .autoCloseStream(Boolean.FALSE).sheet("错误报告")
                    .doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>(8);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 物流车审批通过和驳回操作
     * @param param
     * @param account
     * @return
     */
    @PostMapping(value = "approvalVisitorRecordRequest")
    @ApiOperation(value = "物流车预约审批通过或驳回和取消")
    public ResultJson approvalVisitorRecordRequest(@RequestBody ApprovalParam param, Account account){
        log.info("approvalVisitorRecordRequest() called with parameters => 【param = {}】",param);
        if (ObjectUtil.isNotNull(account)) {
            //设置审批人姓名
            param.setApprovalUserName(account.getName());
        }
        return this.visitorRecordService.approvalVisitorRecordRequest(param);
    }

}
